import React from 'react';
import PropTypes from 'prop-types';
import {Spin, Card, Button, Row, Col, Table} from 'antd';
import {DATE_FORMAT, FILES_API, TABLE} from '../constants';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import routes from './routes';
import {abandonData, getDetail} from './api';
import {injectIntl} from './intl';
import {currency, saleOrderPriceTerms, paymentType, saleOrderTransportTypeForKd, proformaInvoiceSourceKd} from '../Enum';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import {hasPermissions} from './utils';
import {PERMISSION, formatExportExcelUrl, formatExportPdfUrl} from './constants';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import styles from './style.css';
const {Description} = DescriptionList;
export class DetailPanel extends React.PureComponent {
    state = {
        loading: false,
        data: {},
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        details: res.data.saleProformaInvoiceDetails.map(d => Object.assign({}, d, {
                            order: res.data.saleProformaInvoiceDetails.findIndex(x => x.id === d.id) + 1,
                        })),
                        saleProformaPartDetails: res.data.saleProformaPartDetails
                    });
                else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    handleUpdateClick = () => {
        this.props.history.push(routes.update.format(this.props.id));
    }
    handleConfirmClick = () => {
        this.props.history.push(routes.confirm.format(this.props.id));
    }
    onClickAbandonBtn = () => {
        this.setState({loading: true});
        abandonData(this.state.data.id, this.state.data.rowVersion)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    onExportExcel = e => {
        e.stopPropagation();
        window.open(formatExportExcelUrl(e.currentTarget.dataset.id, e.currentTarget.dataset.code));
    }
    onExportPdf = e => {
        e.stopPropagation();
        window.open(formatExportPdfUrl(e.currentTarget.dataset.id, e.currentTarget.dataset.code));
    }
    onClickCreate = () => {
        window.open(`#/dcs/sales/KDSaleOrder/add?piId=${this.props.id}`);
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, saleProformaPartDetails} = this.state;
        let totalAmount = 0;
        let totalQuantity = 0;
        let totalShipmentAmount = 0;
        let totalInsuranceAmount = 0;
        let totalAmountSum = 0;
        if(details)
            details.forEach(v => {
                totalAmount += v.totalPrice;
                totalQuantity += v.quantity;
                totalShipmentAmount += v.shipmentAmountSum;
                totalInsuranceAmount += v.insuranceAmountSum;
                totalAmountSum += v.amountSum;
            });
        const operations = [];
        const columns = [{
            title: formatMessage({
                id: 'detailPanel.column.order',
                defaultMessage: '序号'
            }),
            dataIndex: 'order',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.sourceCode',
                defaultMessage: '源单据编号'
            }),
            dataIndex: 'sourceCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.kdBomCode',
                defaultMessage: 'KDBOM号'
            }),
            dataIndex: 'kdBomCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.descriptionOfGoods',
                defaultMessage: '产品描述'
            }),
            dataIndex: 'descriptionOfGoods',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.quantity',
                defaultMessage: '数量'
            }),
            dataIndex: 'quantity',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.price',
                defaultMessage: '单价'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.totalPrice',
                defaultMessage: '总价'
            }),
            dataIndex: 'totalPrice',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.amountSum',
                defaultMessage: '总金额'
            }),
            dataIndex: 'amountSum',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.remark',
                defaultMessage: '备注'
            }),
            dataIndex: 'remark',
        }];
        const partColumns = [{
            title: formatMessage({
                id: 'newPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'newPanel.column.partName',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'partName',
        }, {
            title: formatMessage({
                id: 'newPanel.column.quantity',
                defaultMessage: '数量'
            }),
            dataIndex: 'quantity',
        }, {
            title: formatMessage({
                id: 'newPanel.column.price',
                defaultMessage: '单价'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text)
        }];
        if(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(data.options, PERMISSION.update))
            operations.push(<Button key="update" onClick={this.handleUpdateClick} size="small">{
                formatMessage({
                    id: 'detailPage.btn.update',
                    defaultMessage: '编辑'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.confirm) && hasPermissions(data.options, PERMISSION.confirm))
            operations.push(<Button key="confirm" onClick={this.handleConfirmClick} size="small">{
                formatMessage({
                    id: 'detailPage.btn.confirm',
                    defaultMessage: '确认'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.exportExcel) && hasPermissions(data.options, PERMISSION.exportExcel))
            operations.push(<Button key="exportExcel" data-id={this.props.id} data-code={this.props.code} onClick={this.onExportExcel} size="small">{
                formatMessage({
                    id: 'detailPage.btn.exportExcel',
                    defaultMessage: '导出Excel'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.exportPdf) && hasPermissions(data.options, PERMISSION.exportPdf))
            operations.push(<Button key="exportPdf" data-id={this.props.id} data-code={this.props.code} onClick={this.onExportPdf} size="small">{
                formatMessage({
                    id: 'detailPage.btn.exportPdf',
                    defaultMessage: '导出Pdf'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(data.options, PERMISSION.abandon))
            operations.push(<WrappedPopconfirm
                key="abandon"
                id={this.props.id}
                placement="topLeft"
                onConfirm={this.onClickAbandonBtn}
                title={formatMessage({
                    id: 'detailPanel.validate.abandon',
                    defaultMessage: '是否确认作废？'
                })}>
                <Button key="abandon" size="small">{
                    formatMessage({
                        id: 'detailPanel.btn.abandon',
                        defaultMessage: '作废'
                    })
                }</Button>
            </WrappedPopconfirm>);
        if(hasPermissions(this.props.permissions, PERMISSION.create) && hasPermissions(data.options, PERMISSION.create) && (data.dataSource === 3))
            operations.push(<Button key="create" data-id={this.props.id} data-code={this.props.code} onClick={this.onClickCreate} size="small">{
                formatMessage({
                    id: 'detailPage.btn.create',
                    defaultMessage: '生成销售订单'
                })
            }</Button>);
        if(data.dataSource !== proformaInvoiceSourceKd.KD索赔单 &&
            (data.salesOrderPriceTerms === saleOrderPriceTerms.CIF ||
                data.salesOrderPriceTerms === saleOrderPriceTerms.CPT ||
                data.salesOrderPriceTerms === saleOrderPriceTerms.CIP ||
                data.salesOrderPriceTerms === saleOrderPriceTerms.CFR))
            columns.splice((data.dataSource === 1 ? 4 : 3), 0,
                {
                    title: formatMessage({
                        id: 'dablePanel.column.containerNumber',
                        defaultMessage: '集装箱数'
                    }),
                    dataIndex: 'containerNumber'
                });
        if(data.dataSource === 2)
            columns.splice(5, 3,
                {
                    title: this.props.intl.formatMessage({
                        id: 'dablePanel.column.laborHour',
                        defaultMessage: '工时'
                    }),
                    dataIndex: 'laborHour',
                },
                {
                    title: this.props.intl.formatMessage({
                        id: 'dablePanel.column.laborPrice',
                        defaultMessage: '工时单价'
                    }),
                    dataIndex: 'laborPrice',
                    render: text => formatAmount(text)
                });
        if(data.salesOrderPriceTerms === 3 || data.salesOrderPriceTerms === 5 || data.salesOrderPriceTerms === 6 || data.salesOrderPriceTerms === 2)
            columns.splice((data.dataSource === 2 ? 9 : 7), 0,
                {
                    title: formatMessage({
                        id: 'detailPanel.column.unitShipmentAmount',
                        defaultMessage: '单位运费'
                    }),
                    dataIndex: 'unitShipmentAmount',
                });
        if(data.salesOrderPriceTerms === 3 || data.salesOrderPriceTerms === 6)
            columns.splice((data.dataSource === 2 ? 10 : 8), 0,
                {
                    title: formatMessage({
                        id: 'detailPanel.column.unitInsuranceAmount',
                        defaultMessage: '单位保费'
                    }),
                    dataIndex: 'unitInsuranceAmount',
                });
        if(data.salesOrderPriceTerms === 3 || data.salesOrderPriceTerms === 5 || data.salesOrderPriceTerms === 6 || data.salesOrderPriceTerms === 2)
            columns.splice((data.dataSource === 2 ? 11 : 9), 0,
                {
                    title: formatMessage({
                        id: 'detailPanel.column.shipmentAmountSum',
                        defaultMessage: '总运费'
                    }),
                    dataIndex: 'shipmentAmountSum',
                });
        if(data.salesOrderPriceTerms === 3 || data.salesOrderPriceTerms === 6)
            columns.splice((data.dataSource === 2 ? 12 : 10), 0,
                {
                    title: formatMessage({
                        id: 'detailPanel.column.insuranceAmountSum',
                        defaultMessage: '总保费'
                    }),
                    dataIndex: 'insuranceAmountSum',
                });
        return (
            <div>
                <Spin spinning={this.state.loading}>
                    <Card>
                        <DescriptionList size="large" title={<Row><Col span={12}>{formatMessage({
                            id: 'detailPanel.text.title',
                            defaultMessage: '基本信息'
                        })}</Col>
                        <Col className={`col-align-right ${styles.detail}`} span={12}>{operations}</Col>
                        </Row>}>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.dataSource',
                                defaultMessage: '数据来源'
                            })}>{conventEnumValueToString(proformaInvoiceSourceKd, data.dataSource)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.code',
                                defaultMessage: 'PI编号'
                            })}>{data.code}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.batchNumber',
                                defaultMessage: '批次号'
                            })}>{data.batchNumber}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.ifUseBatchNumberToPrint',
                                defaultMessage: '使用批次号打印'
                            })}>{data.ifUseBatchNumberToPrint ? formatMessage({
                                    id: 'detailPanel.text.yes',
                                    defaultMessage: '是'
                                }) : formatMessage({
                                    id: 'detailPanel.text.no',
                                    defaultMessage: '否'
                                })}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.brand',
                                defaultMessage: '品牌'
                            })}>{`(${data.brandCode})${data.brandName}`}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.dealerCode',
                                defaultMessage: '总代编号'
                            })}>{data.dealerCode}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.country',
                                defaultMessage: '国家'
                            })}>{data.country}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.marketDepartmentName',
                                defaultMessage: '大区'
                            })}>{data.marketDepartmentName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.countryOfOrigin',
                                defaultMessage: '原产国'
                            })}>{data.countryOfOrigin}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.countryOfDestination',
                                defaultMessage: '目的国'
                            })}>{data.countryOfDestination}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.address',
                                defaultMessage: '地址'
                            })}>{data.address}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.contactNumber',
                                defaultMessage: '电话'
                            })}>{data.contactNumber}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.zipCode',
                                defaultMessage: '邮政编码'
                            })}>{data.zipCode}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.cnpj',
                                defaultMessage: '法人国家登记号'
                            })}>{data.cnpj}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.buyer',
                                defaultMessage: '购买人'
                            })}>{data.buyer}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.contact',
                                defaultMessage: '联系人'
                            })}>{data.contact}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.telex',
                                defaultMessage: '电传'
                            })}>{data.telex}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.currency',
                                defaultMessage: '币种'
                            })}>{conventEnumValueToString(currency, data.currency)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.tradeMethodName',
                                defaultMessage: '贸易方式'
                            })}>{data.tradeMethodName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.salesOrderPriceTerms',
                                defaultMessage: '价格条款'
                            })}>{conventEnumValueToString(saleOrderPriceTerms, data.salesOrderPriceTerms)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.paymentType',
                                defaultMessage: '付款方式'
                            })}>{conventEnumValueToString(paymentType, data.paymentType)}</Description>
                            {(data.saleOrderPriceTerms === 3 || 5 || 6 || 2) && <Description term={formatMessage({
                                id: 'detailPanel.text.shipmentAmount',
                                defaultMessage: '运费汇总'
                            })}><strong>{formatAmount(data.shipmentAmount)}</strong></Description>
                            }
                            {(data.saleOrderPriceTerms === 3 || 6) && <Description term={formatMessage({
                                id: 'detailPanel.text.insuranceAmount',
                                defaultMessage: '保费汇总'
                            })}><strong>{formatAmount(data.insuranceAmount)}</strong></Description>
                            }
                            <Description term={formatMessage({
                                id: 'detailPanel.text.productAmount',
                                defaultMessage: '清单总额'
                            })}><strong>{formatAmount(data.productAmount)}</strong></Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.certificationAmount',
                                defaultMessage: '认证费用'
                            })}><strong>{formatAmount(data.certificationAmount)}</strong></Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.totalAmount',
                                defaultMessage: 'PI金额'
                            })}><strong>{formatAmount(data.totalAmount)}</strong></Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.deliveryTerms',
                                defaultMessage: '运输方式'
                            })}>{conventEnumValueToString(saleOrderTransportTypeForKd, data.deliveryTerms)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.payableAccount',
                                defaultMessage: '到付账号'
                            })}>{data.payableAccount}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.carrierName',
                                defaultMessage: '指定货代'
                            })}>{data.carrierName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.shippingPortName',
                                defaultMessage: '发运港口'
                            })}>{data.shippingPortName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.destinationPort',
                                defaultMessage: '目的港口'
                            })}>{data.destinationPort}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.estimatedDeliveryDate',
                                defaultMessage: '预计交货日期'
                            })}>{formatDateTime(data.estimatedDeliveryDate, DATE_FORMAT)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.validity',
                                defaultMessage: '报价有效期'
                            })}>{formatDateTime(data.validity, DATE_FORMAT)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.createTime',
                                defaultMessage: '提报日期'
                            })}>{formatDateTime(data.createTime, DATE_FORMAT)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.creator',
                                defaultMessage: '提报人'
                            })}>{data.creator}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.commodity',
                                defaultMessage: 'PI描述'
                            })}>{data.commodity}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.packing',
                                defaultMessage: '包装描述'
                            })}>{data.packing}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.confirmor',
                                defaultMessage: '确认人'
                            })}>{data.confirmor}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.confirmTime',
                                defaultMessage: '确认时间'
                            })}>{formatDateTime(data.confirmTime, DATE_FORMAT)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.confirmIdea',
                                defaultMessage: '确认意见'
                            })}>{data.confirmIdea}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.remark',
                                defaultMessage: '备注'
                            })}>{data.remark}</Description>
                        </DescriptionList>
                    </Card>
                    <Card>
                        <DescriptionList size="large" title={<Row><Col span={12}>{formatMessage({
                            id: 'detailPanel.text.bankTitle',
                            defaultMessage: '银行信息'
                        })}</Col>
                        </Row>}>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.bankAccount',
                                defaultMessage: '银行账号'
                            })}>{data.bankAccount}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.bankName',
                                defaultMessage: '银行名称'
                            })}>{data.bankName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.bankNameEng',
                                defaultMessage: '银行英文名称'
                            })}>{data.bankNameEng}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.bankAddress',
                                defaultMessage: '银行地址'
                            })}>{data.bankAddress}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.swift',
                                defaultMessage: '银行识别码'
                            })}>{data.swift}</Description>
                        </DescriptionList>
                    </Card>
                    <Card>
                        <DescriptionList size="large" title={formatMessage({
                            id: 'detailPanel.table.details',
                            defaultMessage: 'PI形式发票清单'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={columns}
                                rowKey="id"
                                pagination={false}
                                dataSource={details}
                                footer={() => <DescriptionList>
                                    <Description term={formatMessage({
                                        id: 'detailPanel.operation.totalQuantity',
                                        defaultMessage: '数量汇总'
                                    })}>{totalQuantity}
                                    </Description>
                                    <Description term={formatMessage({
                                        id: 'detailPanel.operation.totalAmount',
                                        defaultMessage: '总价汇总'
                                    })}><strong>{formatAmount(totalAmount)}</strong>
                                    </Description>
                                    {(data.salesOrderPriceTerms === 3 || data.salesOrderPriceTerms === 5 ||
                                        data.salesOrderPriceTerms === 6 || data.salesOrderPriceTerms === 2) && <Description term={formatMessage({
                                        id: 'detailPanel.operation.totalShipmentAmount',
                                        defaultMessage: '运费汇总'
                                    })}>{formatAmount(totalShipmentAmount)}
                                    </Description>}
                                    {(data.salesOrderPriceTerms === 3 || data.salesOrderPriceTerms === 6) && <Description term={formatMessage({
                                        id: 'detailPanel.operation.totalInsuranceAmount',
                                        defaultMessage: '保费汇总'
                                    })}>{formatAmount(totalInsuranceAmount)}
                                    </Description>}
                                    <Description term={formatMessage({
                                        id: 'detailPanel.operation.totalAmountSum',
                                        defaultMessage: '金额汇总'
                                    })}><strong>{formatAmount(totalAmountSum)}</strong>
                                    </Description>
                                </DescriptionList>}
                                {...TABLE} />
                        </DescriptionList>
                    </Card>
                    <Card>
                        <DescriptionList size="large" title={formatMessage({
                            id: 'detailPanel.table.partDetails',
                            defaultMessage: 'PI备件清单'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={partColumns}
                                rowKey="id"
                                pagination={false}
                                dataSource={saleProformaPartDetails}
                                {...TABLE} />
                        </DescriptionList>
                    </Card>
                    <Card>
                        {data.attachments && data.attachments.length >= 0
                            ? <DescriptionList size="large" title={formatMessage({
                                id: 'detailPanel.card.attachment',
                                defaultMessage: 'PI附件'
                            })}>
                                {data.attachments.map(item => (<Description key={item.fileId}>
                                    <a icon="download" download href={`${FILES_API.files}/${item.fileId}`} size="small">
                                        {item.fileName}</a></Description>))}
                            </DescriptionList>
                            : <DescriptionList title={formatMessage({
                                id: 'detailPanel.content.noAttachment',
                                defaultMessage: '暂无附件'
                            })}>
                            </DescriptionList>}
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Button
                        type="primary"
                        disabled={this.state.loading}
                        onClick={this.props.onCancel}>{formatMessage({
                            id: 'detailPage.text.return',
                            defaultMessage: '返回'
                        })}</Button>
                </div>
            </div>
        );
    }
}

DetailPanel.propTypes = {
    id: PropTypes.string.isRequired,
    permissions: PropTypes.array.isRequired,
    onCancel: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    successReturn: PropTypes.func,
};

import {connect} from 'react-redux';
import {
    tableSearch
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);

const mapStateToProps = (state, props) => ({
    id: props.id,
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    permissions: getPermissions(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DetailPanel));
